package com.example.xjtuse_pc.services;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.os.SystemClock;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xjtuse_pc.db.dao.NumberAddressQueryUtils;
import com.example.xjtuse_pc.mobilesafe.R;

/**
 * Created by XJTUSE-PC on 2016/4/3.
 */
public class AddressService extends Service {
    private SharedPreferences sp;
    private TelephonyManager tm;
    private MyListener listener;
    private MyBroadtcost Broadtcost;
    private WindowManager wm;
    private View tv;
    private WindowManager.LayoutParams params;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class MyBroadtcost extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String phone = getResultData();
            String name = NumberAddressQueryUtils.queryNumber(phone);
            // Toast.makeText(context,name,Toast.LENGTH_LONG).show();
            MyToast(name);
        }
    }
    long[] mHits = new long[2];

    //自定义Toast
    private void MyToast(String result) {

        int[] items = {R.drawable.call_locate_white, R.drawable.call_locate_orange, R.drawable.call_locate_blue,
                R.drawable.call_locate_gray, R.drawable.call_locate_green};

        tv = View.inflate(this, R.layout.toast_address, null);
        tv.setOnClickListener(new View.OnClickListener() {
            int startX;
            @Override
            public void onClick(View v) {
                /**
                 *  System.arraycopy(src,int srcPos,dst,int dstPos,int length)
                 *  将数组src拷贝给dst
                 *  src目标数组，srcPos目标数组开始拷贝位置
                 *  dst拷贝数组，dstPos拷贝存储数组中位置
                 *  length要拷贝的长度
                  */

                System.arraycopy(mHits,1,mHits,0,mHits.length-1);
                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                //SystemClock.uptimeMillis开机后cpu运行时间
                if(mHits[0]>=(SystemClock.uptimeMillis()-500)){
                    //双击居中
                    params.x = 0;
                    wm.updateViewLayout(tv, params);
                    SharedPreferences.Editor ed = sp.edit();
                    ed.putInt("startX", 0);
                    ed.commit();

                }


            }
        });

        tv.setOnTouchListener(new View.OnTouchListener() {
            int startX, startY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN://按下后记录x,y坐标
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        int newX = (int) event.getRawX();
                        int newY = (int) event.getRawY();
                        int dx = newX - startX;
                        int dy = newY - startY;
                        params.x = params.x + dx;
                        params.y = params.y + dy;
//                        if (params.x < 0) {
//                            params.x = 0;
//                        }
//                        if (params.y < 0) {
//                            params.y = 0;
//                        }
//                        if (params.x > (wm.getDefaultDisplay().getHeight() - tv.getHeight())) {
//                            params.x = wm.getDefaultDisplay().getHeight() - tv.getHeight();
//                        }
//                        if (params.y > (wm.getDefaultDisplay().getWidth() - tv.getWidth())) {
//                            params.y = wm.getDefaultDisplay().getWidth() - tv.getWidth();
//                        }
                        wm.updateViewLayout(tv, params);
                        startX = (int) event.getRawX();
                        startY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP://将最新位记录
                        SharedPreferences.Editor ed = sp.edit();
                        ed.putInt("startX", startX - wm.getDefaultDisplay().getWidth() / 2);
                        ed.putInt("startY", startY - wm.getDefaultDisplay().getHeight() / 2);
                        ed.commit();
                        break;
                }

                return false;
            }
        });

        TextView textView = (TextView) tv.findViewById(R.id.tv_toast);
        textView.setText(result);
        int which = sp.getInt("which", 0);
        tv.setBackgroundResource(items[which]);
        params = new WindowManager.LayoutParams();
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        params.format = PixelFormat.TRANSLUCENT;
        params.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE;
        params.x = sp.getInt("startX", 0);
        params.y = sp.getInt("startY", 0);
        wm.addView(tv, params);
    }

    private class MyListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //第一个是状态参数，第二个是电话号
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    //得到号码显示归属地
                    String result = NumberAddressQueryUtils.queryNumber(incomingNumber);
//                    Toast.makeText(AddressService.this, result, Toast.LENGTH_LONG).show();
                    MyToast(result);
                    break;
                case TelephonyManager.CALL_STATE_IDLE://电话空闲状态 关闭Toast
                    if (tv != null) {
                        wm.removeView(tv);
                    }
                    break;

            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sp = getSharedPreferences("config", MODE_PRIVATE);
        Log.i("join", "service开启");
        Broadtcost = new MyBroadtcost();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        registerReceiver(Broadtcost, filter);

        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        listener = new MyListener();
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
        //实例化窗体
        wm = (WindowManager) getSystemService(WINDOW_SERVICE);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        tm.listen(listener, PhoneStateListener.LISTEN_NONE);
        listener = null;


    }

}
